package com.fz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fz.entity.GoodsReview;
import com.fz.entity.Orders;
import com.fz.mapper.GoodsReviewMapper;
import com.fz.service.GoodsReviewService;
import com.fz.service.OrdersService;
import com.fz.vo.ResultVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

@Service
public class GoodsReviewServiceImpl extends ServiceImpl<GoodsReviewMapper, GoodsReview> implements GoodsReviewService {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private GoodsReviewMapper goodsReviewMapper;

    @Override
    public ResultVo<Boolean> addReview(GoodsReview review) {
        // 验证订单状态是否已完成
        Orders order = ordersService.getById(review.getOrderId());
        if (order == null || !"已完成".equals(order.getOrderStatus())) {
            return ResultVo.failed("订单未完成，不能评价");
        }

        // 检查是否已评价
        QueryWrapper<GoodsReview> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id", review.getOrderId());
        if (count(wrapper) > 0) {
            return ResultVo.failed("该订单已评价");
        }
//        review.setCreateTime(LocalDateTime.now());
//        review.setUpdateTime(LocalDateTime.now());
        save(review);
        return ResultVo.success(true);
    }

    @Override
    public IPage<GoodsReview> getByProductId(Long productId, Integer page, Integer size) {
        QueryWrapper<GoodsReview> wrapper = new QueryWrapper<>();
        wrapper.eq("product_id", productId)
                .orderByDesc("create_time");
        System.out.println("进入商品评价service");
        return page(new Page<>(page, size), wrapper);
    }

    @Override
    public ResultVo<Boolean> canReview(Long orderId) {
        // 1. 检查订单是否已完成
        Orders order = ordersService.getById(orderId);
        if (order == null || !"已完成".equals(order.getOrderStatus())) {
            return ResultVo.success(false);
        }

        // 2. 检查是否已评价
        QueryWrapper<GoodsReview> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id", orderId);
        boolean canReview = count(wrapper) == 0;
        return ResultVo.success(canReview);
    }

    @Override
    public List<GoodsReview> getLatestReviews(Long productId, int limit) {
        return goodsReviewMapper.getLatestReviews(productId, limit);
    }

    @Override
    public Double getAverageRating(Long productId) {
        return goodsReviewMapper.getAverageRating(productId);
    }

    @Override
    public Map<Long, int[]> getRatingDistribution() {
        // 查询所有商品的评分分布
        List<Map<Long, Object>> distributionList = baseMapper.getRatingDistribution();

        // 转换为 Map<商品ID, 评分数组>
        Map<Long, int[]> result = new HashMap<>();
        for (Map<Long, Object> item : distributionList) {
            Long productId = Long.valueOf(item.get("product_id").toString());
            int rating = ((Number) item.get("rating")).intValue();
            int count = ((Number) item.get("count")).intValue();

            // 初始化评分数组
            int[] ratings = result.computeIfAbsent(productId, k -> new int[5]);

            // 将1-5星映射到数组索引0-4
            if (rating >= 1 && rating <= 5) {
                ratings[rating - 1] = count;
            }
        }

        return result;
    }
}